import React, {Component} from "react";
import {reqCategorys, reqAddOrUpdateProduct} from "../../api";
import {Card, Icon, Form, Input, Cascader, Button, message} from 'antd';
import LinkButton from "../../components/link-button";
import PicturesWall from "./pictures-wall";
import RichTextEditor from "./rich-text-editor";

const Item = Form.Item;
const TextArea = Input.TextArea;


class ProductAddUpdate extends Component {
    constructor(props) {
        super(props);
        this.pw = React.createRef();
        this.editor = React.createRef();
    }

    state = {
        options: [],
    };

    handleSubmit = async (event) => {
        event.preventDefault();

        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                const {name,desc,price,categoryIds} = values;
                let categoryId,pCategoryId;
                if (categoryIds.length === 1) {
                    pCategoryId = '0';
                    categoryId = categoryIds[0];
                } else {
                    pCategoryId = categoryIds[0];
                    categoryId = categoryIds[1];
                }
                const imgs = this.pw.current.getImgs();
                const detail = this.editor.current.getDetail();
                const product = {name, desc, price, imgs, detail, pCategoryId, categoryId};
                console.info(product);
                if (this.isUpdate) {
                    product._id = this.product._id;
                }

                const result = await reqAddOrUpdateProduct(product);
                if (result.status === 0) {
                    message.success(`${this.isUpdate ? '更新商品成功':'新增商品成功'}`);
                    this.props.history.goBack();
                } else {
                    message.error(`${this.isUpdate ? '更新商品失败':'新增商品失败'}`);
                }
            } else {
                console.log('校验失败')
            }
        });
    };

    validatePrice = (rule, value, callback) => {
        if (value * 1 > 0) {
            callback();
        } else {
            callback('价格必须大于0');
        }
    };

    initOptions = async (categorys) => {
        const options = categorys.map(item => ({
            value: item._id,
            label: item.name,
            isLeaf: false,
        }));

        const {isUpdate, product} = this;
        const {pCategoryId, categoryId} = product;
        if (isUpdate && pCategoryId !== '0') {
            const subCategorys = await this.getCategorys(pCategoryId);
            const childOptions = subCategorys.map(item => ({
                value: item._id,
                label: item.name,
                isLeaf: true,
            }));

            const targetOption = options.find(option => option.value === pCategoryId);
            targetOption.children = childOptions;
        }
        this.setState({options});
    };

    getCategorys = async (parentId) => {
        const result = await reqCategorys(parentId);
        if (result.status === 0) {
            const categorys = result.data;
            if (parentId === '0') {
                this.initOptions(categorys);
            } else {
                return categorys;
            }
        } else {
            message.error('获取分类数据失败')
        }
    };

    loadData = async selectedOptions => {
        const targetOption = selectedOptions[0];
        targetOption.loading = true;

        const subCategorys = await this.getCategorys(targetOption.value);
        targetOption.loading = false;
        if (subCategorys && subCategorys.length > 0) {
            const childOptions = subCategorys.map(item => ({
                value: item._id,
                label: item.name,
                isLeaf: true,
            }));
            targetOption.children = childOptions;
        } else {
            targetOption.isLeaf = true;
        }

        this.setState({
            options: [...this.state.options],
        });
    };

    onChange = (value, selectedOptions) => {
        console.log(value, selectedOptions);
    };

    componentDidMount() {
        this.getCategorys('0');
    }

    componentWillMount() {
        const product = this.props.location.state;
        this.isUpdate = !!product;
        this.product = product || {};
    }

    render() {
        const categoryIds = [];
        const {isUpdate, product} = this;
        const {pCategoryId, categoryId, imgs, detail} = product;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 2 },
            wrapperCol: { span: 8 },
        };

        if (isUpdate) {
            if(pCategoryId === '0') {
                categoryIds.push(categoryId);
            } else {
                categoryIds.push(pCategoryId);
                categoryIds.push(categoryId);
            }
        }

        const title = (
            <span>
                <LinkButton>
                    <Icon type='arrow-left' style={{ marginRight:10, fontSize:20}} onClick={()=>this.props.history.goBack()}/>
                </LinkButton>

                <span>{isUpdate ? '修改商品' : '添加商品'}</span>
            </span>
        );


        return (
            <Card title={title}>
                <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                    <Item label="商品名称：">
                        {
                            getFieldDecorator('name', {
                                rules: [
                                    { required: true, whitespace: true, message: '请输入商品名称' }
                                ],
                                initialValue: product.name
                            }) (
                                <Input placeholder='请输入商品名称'/>
                            )
                        }
                    </Item>
                    <Item label="商品描述：">
                        {
                            getFieldDecorator('desc', {
                                rules: [
                                    { required: true, whitespace: true, message: '请输入商品描述' }
                                ],
                                initialValue: product.desc
                            }) (
                                <TextArea placeholder='请输入商品描述' autoSize={{ minRows: 2, maxRows: 6 }}/>
                            )
                        }
                    </Item>
                    <Item label="商品价格：">
                        {
                            getFieldDecorator('price', {
                                rules: [
                                    { required: true, whitespace: true, message: '请输入商品价格' },
                                    { validator: this.validatePrice },
                                ],
                                initialValue: product.price
                            }) (
                                <Input type='number' addonAfter="元" placeholder='请输入商品价格'/>
                            )
                        }
                    </Item>
                    <Item label="商品分类：">
                        {
                            getFieldDecorator('categoryIds', {
                                rules: [
                                    { required: true, message: '请选择商品分类' },
                                ],
                                initialValue: categoryIds
                            }) (
                                <Cascader
                                    placeholder='请指定商品分类'
                                    options={this.state.options}
                                    loadData={this.loadData}
                                />
                            )
                        }
                    </Item>
                    <Item label='商品图片'>
                        <PicturesWall ref={this.pw} imgs={imgs}/>
                    </Item>
                    <Item label='商品详情' labelCol={{span: 2 }} wrapperCol={{ span: 20 }}>
                        <RichTextEditor ref={this.editor} detail={detail}/>
                    </Item>
                    <Item>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Item>
                </Form>
            </Card>
        );
    }
}

export default Form.create()(ProductAddUpdate);